package com.css.ids.server.common.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.css.apps.base.ip.model.SIp;
import com.css.core.configuration.ConfigurationManager;
import com.css.ids.server.service.dao.IdsIpDao;

public class IPFilter implements Filter {
	public static List<String> ipPatterns;

	public IPFilter() {
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		if (ipPatterns == null) {
			List<SIp> ips = IdsIpDao.getIp();
			if (ips != null) {
				ipPatterns = new ArrayList<String>();
				for (SIp ip : ips) {
					ipPatterns.add(ip.getIp());
				}
			}
		}
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		if ("false"
				.equals(ConfigurationManager.getConfigurationManager().getSysConfigure("app.ids.ipfilter", "false"))) {
			filterChain.doFilter(request, response);
		}
		String ip = IPHelper.getIpAddr(request);
		if (IPHelper.isMatch(ipPatterns, ip)) {
			filterChain.doFilter(request, response);
		} else {
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "ip error!");
			// response.sendRedirect("../casBadWorkstationView.jsp");
		}
	}

	public void destroy() {
	}
}